package com.itheima.aspect;

import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Component
//@Aspect
public class LoginLogAspect {
    @Autowired
    private LoginMapper loginMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = 0L, endTime, costTime;
        Result result = null;
        try {
            //记录操作日志，收集操作日志信息，添加到操作日志数据表中
            startTime = System.currentTimeMillis();
            result = (Result) joinPoint.proceed();
        } finally {
            //需要在finally代码块中放置业务的结束时间，否则在登录异常一行代码时，将不会再执行try中的代码
            endTime = System.currentTimeMillis();
            //获取目标方法耗时
            costTime = endTime - startTime;
            //定义令牌参数token
            String token = "";

            //判断result是否为空，为空时，则自行创建一个登录失败的Result对象，否则登陆成功，从result中获取token值
            if (result == null) {
                result = Result.error("登录失败");
            } else {
                Map data = (Map) result.getData();
                token = (String) data.get("token");
            }

            //定义登录日志对象，收集登录日志信息
            EmpLoginLog empLoginLog = new EmpLoginLog();
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setCostTime(costTime);

            Object[] args = joinPoint.getArgs();
            Emp emp = (Emp) args[0];
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());

            int code = result.getCode();
            empLoginLog.setIsSuccess((short) code);
            empLoginLog.setJwt(token);

            //调用登录日志的持久层接口，将登录日志数据保存到数据库中
            loginMapper.insert(empLoginLog);
        }
        return result;
    }
}
